<template>
	<view class="page-container">
		<view class="address-item" v-for="(item, i) in addressList" :key="i">
			<u-row>
				<u-col :span="1" @click="onClickRow(item.id)">
					<radio :checked="item.id == chosenAddressId" v-if="isChosenAddress"></radio>
					<text v-else>{{ i }}</text>
				</u-col>
				<u-col :span="10" @click="onClickRow(item.id)">
					<view class="row-top">
						<view class="name">{{ item.name }}</view>
						<view class="tel">{{ item.tel }}</view>
						<u-tag text="默认" type="error" size="mini" v-if="item.isDefault"></u-tag>
					</view>
					<view class="row-bottom">{{ item.address }}</view>
				</u-col>
				<u-col :span="1"><u-icon name="edit-pen" :size="28" color="#999999" @click="onEdit(item.id)"></u-icon></u-col>
			</u-row>
		</view>
		<u-button type="primary" text="选择" @click="onSelect" v-if="!!chosenAddressId"></u-button>
		<u-gap height="10"></u-gap>
		<u-button type="primary" icon="plus" text="新建收货地址" @click="onAdd"></u-button>
	</view>
</template>

<script>
//获取地址列表
import * as AddressAPI from '@/api/address.js';

export default {
	data() {
		return {
			chosenAddressId: null,
			isChosenAddress: false,
			addressList: []
		};
	},
	onLoad(options) {
		this.chosenAddressId = options.addressId || null;
		console.log('onLoad : chosenAddressId ', this.chosenAddressId);
		this.isChosenAddress = !!this.chosenAddressId;
		this.getAddressList();
	},
	onShow() {
		this.getAddressList();
	},
	methods: {
		getAddressList() {
			AddressAPI.getAddressList().then(result => {
				// console.log(result)
				this.addressList = [];
				result.data.forEach(item => {
					this.addressList.push({
						id: item.id,
						name: item.name,
						tel: item.tel,
						address: item.city + item.county + item.address_detail,
						isDefault: item.is_default == 1 ? true : false
					});
				});
			});
		},

		onEdit(id) {
			uni.$u.route({
				url: '/pages/address/AddressEdit',
				params: {
					id: id
				}
			});
		},
		onAdd() {
			uni.$u.route({
				url: '/pages/address/AddressEdit'
			});
		},

		onClickRow(id) {
			if (this.isChosenAddress) {
				this.chosenAddressId = id;
			}
		},
		onSelect() {
			//?addressId=" + this.chosenAddressId  参数如何传过去？？？？？？？？
			// 建议通过页面通信，事件监听机制

			// 关闭当前页面，返回上一页面
			uni.navigateBack({
				delta: 1 //url:"/pages/order/OrderCreate"
			});
			uni.$emit('addressChanged', { addressId: this.chosenAddressId });
		}
	}
};
</script>

<style lang="scss" scoped>
.page-container {
	padding: 15px 15px 15px 15px;
}

.address-item {
	margin: 10px 0;
	padding-bottom: 10px;
	border-bottom: 1px solid $u-border-color;
}

.row-top {
	display: flex;
	flex-direction: row;
	font-weight: bold;
	font-size: 16px;
	.tel {
		margin: 0 20px;
	}
}

.row-bottom {	
	margin-top: 5px;
	font-size: 14px;
	color: $u-tips-color;
}
</style>
